package com.vc.videosdk.utils;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * @Author : wy
 * @Time : On 2024/9/27 15:14
 * @Description : KeyboardUtil
 */
public final class KeyboardUtil {


    public static void showSoftInput(View view) {

        if (view == null) return;

        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm == null) return;

        view.setFocusable(true);

        view.setFocusableInTouchMode(true);

        view.requestFocus();

        imm.showSoftInput(view, 0, new SoftInputReceiver(view.getContext()));

        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

    }


    private static class SoftInputReceiver extends ResultReceiver {

        private Context context;

        public SoftInputReceiver(Context context) {

            super(new Handler());

            this.context = context;

        }


        @Override

        protected void onReceiveResult(int resultCode, Bundle resultData) {

            super.onReceiveResult(resultCode, resultData);

            if (resultCode == InputMethodManager.RESULT_UNCHANGED_HIDDEN

                    || resultCode == InputMethodManager.RESULT_HIDDEN) {

                toggleSoftInput(context);

            }

            context = null;

        }

    }


    public static void toggleSoftInput(Context context) {

        if (context == null) return;

        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm == null) return;

        imm.toggleSoftInput(0, 0);
    }


    public static void hideSoftInput(View view) {

        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

    }

    public static void hideSoftInput(Window window) {

        View view = window.getCurrentFocus();

        if (view == null) {

            View decorView = window.getDecorView();

            View focusView = decorView.findViewWithTag("keyboardTagView");

            if (focusView == null) {

                view = new EditText(window.getContext());

                view.setTag("keyboardTagView");

                ((ViewGroup) decorView).addView(view, 0, 0);
            } else {
                view = focusView;
            }

            view.requestFocus();
        }

        hideSoftInput(view);
    }

}


